<template>
  <div class="app-container">
    <div class="div-table">
      <el-tabs v-model="editableTabsValue" type="border-card">
        <el-tab-pane
          v-for="(item, index) in editableTabs"
          :key="item.name"
          :label="item.title"
          :name="item.name"
          v-html="item.content"
        />
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { getDetail } from '@/api/systemapi/job'
export default {
  data() {
    return {
      editableTabsValue: '0',
      // 显示数据
      editableTabs: [],
      tabIndex: 0,
      jobId: '',
      // 任务详情
      jobDetail: {},
      // 定时器
      timer: null
    }
  },
  // 页面初始化时执行
  created() {
    this.jobId = this.getUrlKey('jobId')
    this.fetchJobDetail(this.jobId)
    // 轮询，渲染执行结果
    this.rollQueryJobDetail(this.jobId)
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event)
    },
    fetchJobDetail(jobId) {
      getDetail(jobId).then(response => {
        this.jobDetail = response.data
        this.editableTabs = []
        for (var i = 0; i < response.data.tasks.length; i++) {
          var row = {}
          row.title = response.data.tasks[i].host.ipaddr
          row.name = response.data.tasks[i].id.toString()
          row.content = response.data.tasks[i].log.replace(/(\r\n)|(\n)/g, '<br>')
          row.status = response.data.tasks[i].status
          // if (row.content === "") {
          //     row.content = "任务执行中..."
          // }
          if (row.status === 'running' || row.status === 'created') {
            row.content += '任务执行中...'
          }
          this.editableTabs.push(row)
        }
      })
    },
    rollQueryJobDetail(jobId) {
      if (this.timer) {
        clearInterval(this.timer)
      } else {
        this.timer = setInterval(() => {
          // 在这里发送请求获取数据
          this.fetchJobDetail(jobId)
          if (this.jobDetail.status === 'succeed') {
            clearInterval(this.timer)
            this.timer = null
            this.$message({
              message: '任务执行成功',
              type: 'success'
            })
          } else if (this.jobDetail.status === 'faild') {
            clearInterval(this.timer)
            this.timer = null
            this.$message({
              message: '任务执行失败',
              type: 'error'
            })
          }
        }, 5000)
      }
    },
    getUrlKey(name) {
      return decodeURIComponent(
        (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  width: 100%;
  .div-table {
    flex: 1;
  }
  .el-tab-pane {
    background-color: #2f3a48;
    color:#bfcbd9;
    font-size: 18px;
    opacity: 1;
    padding: 10px 20px;
    min-height: 1000px;
  }
}

</style>
